<?php

namespace App\Listeners;

use App\Events\OrderEvent;
use App\Library\User\AchievementManager;
use App\Library\User\CommissionManager;
use App\Library\User\PointManager;
use App\Library\User\UserGroupManager;
use App\WeChat\WechatDefaultConfig;
use App\WechatMessages\ZPH\OrderCreatedMessage;
use App\WechatMessages\ZPH\OrderPaidMessage;
use App\WechatMessages\ZPH\OrderReceivedMessage;
use App\WechatMessages\ZPH\OrderRefundCompletedMessage;
use App\WechatMessages\ZPH\OrderRefundCreatedMessage;
use App\WechatMessages\ZPH\OrderSendMessage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class OrderEventListener
{
    use WechatDefaultConfig;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  OrderEvent $event
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle(OrderEvent $event)
    {
        $order = $event->order;

        //创建订单
        if ($event->type == 'created')
        {
            $connect = $order->buyer->connect;
            if ($connect) {
                $item = $order->items()->first();
                $message = new OrderCreatedMessage();
                $message->setTouser($connect->openid);
                $message->setProductName($item ? $item->title : '');
                $message->setAmount($order->total_fee);
                $message->setOrderTime(@date('Y-m-d H:i:s', $order->created_at));
                $message->setOrderNo($order->order_no);
                $message->setUrl(url('h5/bought/detail?order_id='.$order->order_id));
                $this->officialAccount()->template_message->send($message->getMsgContent());
            }
        }

        //支付订单
        if ($event->type == 'paid')
        {
            //付款减库存
            $shop = $event->order->shop;
            $order->items()->with('item')->get()->map(function ($item) use (&$shop){
                if ($item->item)
                {
                    $item->item->sold+= $item->quantity;
                    if ($item->item->stock >= $item->quantity)
                    {
                        $item->item->stock -= $item->quantity;
                    } else {
                        $item->item->stock = 0;
                    }
                    $item->item->save();
                }
                $shop->total_sold+= $item->quantity;
            });
            $shop->save();

            //发送模板消息
            $connect = $order->buyer->connect;
            if ($connect) {
                $item = $order->items()->first();
                $message = new OrderPaidMessage();
                $message->setTouser($connect->openid);
                $message->setShopName($order->shop_name);
                $message->setProductName($item ? $item->title : '');
                $message->setAmount($order->total_fee);
                $message->setIntegral($order->total_fee);
                $message->setTradeTime(@date('Y-m-d H:i:s', $order->created_at));
                $message->setUrl(url('h5/bought/detail?order_id='.$order->order_id));
                $event->order->buyer->sendTemplateMessage($message);
            }
        }

        if ($event->type == 'send')
        {
            $connect = $order->buyer->connect;
            if ($connect)
            {
                $item = $order->items()->first();
                $shipping = $order->shipping;
                $express = $shipping->express;

                $message = new OrderSendMessage();
                $message->setTouser($connect->openid);
                $message->setProductName($item ? $item->title : '');
                $message->setExpressName($express->name);
                $message->setExpressNo($shipping->express_no);
                $message->setAddress($shipping->province.$shipping->city.$shipping->district.$shipping->street);
                $message->setUrl(url('h5/bought/detail?order_id='.$order->order_id));
                $this->officialAccount()->template_message->send($message->getMsgContent());
            }
        }

        //确认收货到货物，交易成功
        if ($event->type == 'received')
        {
            $buyer = $order->buyer;
            //更新会员等级
            UserGroupManager::upgrade($buyer);
            //获得会员积分
            PointManager::addConsumptionPoints($buyer, $order->total_fee);
            //上级用户获得佣金
            CommissionManager::addConsumptionCommission($order);
            //增加个人节点业绩
            AchievementManager::addNodeAchievement($buyer, $order->total_fee);

            //发送模板消息
            $connect = $order->buyer->connect;
            if ($connect)
            {
                $message = new OrderReceivedMessage();
                $message->setTouser($connect->openid);
                $message->setOrderNo($order->order_no);
                $message->setTradeTime(@date('Y-m-d H:i:s'));
                $message->setUrl(url('h5/bought/detail?order_id='.$order->order_id));
                $this->officialAccount()->template_message->send($message->getMsgContent());
            }
        }

        if ($event->type == 'refunding')
        {

            $refund = $order->refund;
            if ($refund)
            {
                $message = new OrderRefundCreatedMessage();
                $message->setOrderNo($order->order_no);
                $message->setShopName($order->shop_name);
                $message->setTradeAmount($order->total_fee);
                $message->setRefundAmount($refund->refund_amount);
                $message->setTime(date('Y-m-d H:i:s'));
                $message->setUrl(url('h5/bought/detail?order_id='.$order->order_id));
                $order->buyer->sendTemplateMessage($message);
            }
        }

        if ($event->type == 'refunded')
        {
            //退货恢复库存
            $order->items()->with('item')->get()->map(function ($item) use (&$shop){
                if ($item->item)
                {
                    $item->item->stock += $item->quantity;
                    $item->item->save();
                }
            });

            $refund = $order->refund;
            if ($refund)
            {
                $message = new OrderRefundCompletedMessage();
                $message->setRefundReason($refund->refund_reason);
                $message->setRefundAmount($refund->refund_amount.'元');
                $message->setUrl(url('h5/bought/detail?order_id='.$order->order_id));
                $order->buyer->sendTemplateMessage($message);
            }
        }
    }
}
